const express = require('express')
const server = express()
const jsonServer = require('json-server')
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

const jwt = require('jsonwebtoken')
const expressJWT = require('express-jwt')
var svgCaptcha = require('svg-captcha');

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

let dbData = require('./db.json')

const secretKey = 'itheima No1 ^_^'

let yzm = ''

server.set('host', '192.168.32.29');
server.use(middlewares)
server.use(express.json())

server.use('/api', (req, res) => {
  res.redirect(req.url)
  return
})

// 判断用户名是否注册和是否为空 新注册的不能判断
server.post('/login', (req, res, next) => {
  let flag = true;
  let data = req.body

  if (data.yzm !== yzm) {
    res.jsonp({
      status: 400,
      message: '验证码错误'
    })
    return
  }

  if (data.username && data.password) {
    dbData.login.forEach(v => {
      if (v.username === data.username) {
        flag = false
      }
    })
    if (!flag) {
      res.jsonp({
        status: 400,
        message: '该用户名已被注册'
      })
      return
    }
    req.body = {
      "username": req.body.username,
      "password": req.body.password,
      "email": req.body.email,
      "tel": req.body.tel,
      "account": 183 + random(7),
      "rightIds": [],
      "position": "打工仔",
      "state": "正常",
    }

    next()
  } else {
    res.jsonp({
      status: 400,
      message: '用户名或密码不能为空'
    })
    return
  }
})

// 验证码
server.get('/captcha', (req, res) => {
  let captcha = svgCaptcha.create();
  yzm = captcha.text;
  res.type('svg');
  res.status(200).send(captcha.data);
  return
});

server.post('/', (req, res, next) => {

  if (req.url.startsWith('/shoporder')) {
    req.body.orderId = O + random(10)
  } else if (req.url.startsWith('/shoplist')) {
    req.body.shopId = S + random(10)
  } else if (req.url.startsWith('/industryInvolved')) {
    req.body.industryId = I + random(10)
  } else if (req.url.startsWith('/goodsList')) {
    req.body.goodsId = G + random(10)
  } else if (req.url.startsWith('/goodsType')) {
    req.body.typeId = T + random(10)
  } else if (req.url.startsWith('/shopEquities')) {
    req.body.equitiesId = E + random(10)
  } else if (req.url.startsWith('/businessdistrict')) {
    req.body.userId = U + random(10)
  }

  next()
})

server.use(expressJWT({ secret: secretKey, algorithms: ['HS256'] }).unless({
  path: ['/login', '/yzm', /^\/goodsType/, /^\/goodsList/, /^\/shoporder/, /^\/shoplist/, /^\/platformExpenseList/,
    /^\/discountList/, /^\/tableData/, /^\/platformIncomeList/, /^\/industryInvolved/, /^\/captcha/, /^\/materialList/
    , /^\/tsRecordForm/, /^\/officialmaterialList/, /^\/shopEquities/, /^\/withDrawList/,
    /^\/userList/, /^\/ordersStatistics/, /^\/businessdistrict/, /^\/storeCoupon/, /^\/universalCoupon/, /^\/rightList/,
    '/db']
}))
// server.use(expressJWT({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: ['/login',/([\s\S]*)/] }))


function jiekou(req, res, msg, path) {
  let result = {}
  if (req.method === 'GET') {
    console.log('获取' + msg)
    result = {
      status: 200,
      message: '获取' + msg + '成功',
      total: dbData[path].length,
      data: res.locals.data,
    }
  } else if (req.method === 'POST') {
    console.log('添加' + msg)
    dbData = db.read().__wrapped__
    result = {
      status: 200,
      message: '添加' + msg + '成功',
      time: new Date()
    }
  } else if (req.method === 'DELETE') {
    console.log('删除' + msg)
    if (res.statusCode === 404 || res.statusCode === 500) {
      result = {
        status: 400,
        message: '删除' + msg + '失败'
      }
    }
    dbData = db.read().__wrapped__
    result = {
      status: 200,
      message: '删除' + msg + '成功'
    }
  } else if (req.method === 'PATCH') {
    console.log('修改' + msg)
    result = {
      status: 200,
      message: '修改' + msg + '成功'
    }
  }

  return res.jsonp(result)
}

function random(max) {
  let str = '';
  for (let i = 0; i < max; i++) {
    str += Math.floor(Math.random() * max);
  }
  return str
}


router.render = (req, res) => {
  // console.log(res.locals.data)
  console.log(req.method, req.url)

  // 登录注册接口
  if (req.url.startsWith('/login')) {
    if (req.method === 'GET') {
      const userinfo = req.query
      if (userinfo.username && userinfo.password) {
        if (res.locals.data.length === 0) {
          res.status(401).jsonp({
            status: 401,
            message: '用户名或密码错误'
          })
        } else {
          const tokenStr = jwt.sign({ username: userinfo.username }, secretKey, { expiresIn: '7200s' })
          res.jsonp({
            status: 200,
            message: '登录成功',
            token: tokenStr
          })
        }
      }
      //  判断用户是否注册 
      else {
        if (userinfo.username && res.locals.data.length === 0) {
          res.jsonp({
            status: 200,
            message: '用户名已被注册',
          })
        } else if (userinfo.username) {
          res.jsonp({
            status: 200,
            message: '用户名未被注册',
          })
        }
      }

    }
    // 注册成功
    else if (req.method === 'POST') {
      dbData = db.read().__wrapped__
      res.jsonp({
        status: 200,
        message: '注册成功'
      })
    }
  }// 店铺列表
  else if (req.url.startsWith('/shoplist')) {
    jiekou(req, res, '商铺', 'shoplist')
  }// 订单列表
  else if (req.url.startsWith('/shoporder')) {
    jiekou(req, res, '订单', 'shoporder')
  }// 平台支出
  else if (req.url.startsWith('/platformExpenseList')) {
    jiekou(req, res, '平台支出', 'platformExpenseList')
  }// 优惠券
  else if (req.url.startsWith('/discountList')) {
    jiekou(req, res, '优惠券', 'discountList')
  }// 优惠券
  else if (req.url.startsWith('/tableData')) {
    jiekou(req, res, '优惠券', 'tableData')
  }// 平台收入
  else if (req.url.startsWith('/platformIncomeList')) {
    jiekou(req, res, '平台收入', 'platformIncomeList')
  }// 涉及的行业
  else if (req.url.startsWith('/industryInvolved')) {
    jiekou(req, res, '行业', 'industryInvolved')
  }// 商品
  else if (req.url.startsWith('/goodsList')) {
    jiekou(req, res, '商品', 'goodsList')
  }// 素材
  else if (req.url.startsWith('/materialList')) {
    jiekou(req, res, '素材', 'materialList')
  }// 支出交易记录
  else if (req.url.startsWith('/tsRecordForm')) {
    jiekou(req, res, '支出交易记录', 'tsRecordForm')
  }// 商品分类
  else if (req.url.startsWith('/goodsType')) {
    jiekou(req, res, '商品分类', 'goodsType')
  }// officialmaterialList
  else if (req.url.startsWith('/officialmaterialList')) {
    jiekou(req, res, 'officialmaterialList', 'officialmaterialList')
  }// 店铺权益
  else if (req.url.startsWith('/shopEquities')) {
    jiekou(req, res, '店铺权益', 'shopEquities')
  }// 提现交易列表
  else if (req.url.startsWith('/withDrawList')) {
    jiekou(req, res, '提现交易列表', 'withDrawList')
  }// 用户列表
  else if (req.url.startsWith('/userList')) {
    jiekou(req, res, '用户列表', 'userList')
  }// 订单统计
  else if (req.url.startsWith('/ordersStatistics')) {
    jiekou(req, res, '订单统计', 'ordersStatistics')
  }// 个人商圈
  else if (req.url.startsWith('/businessdistrict')) {
    jiekou(req, res, '个人商圈', 'businessdistrict')
  }// 店铺优惠券
  else if (req.url.startsWith('/storeCoupon')) {
    jiekou(req, res, '店铺优惠券', 'storeCoupon')
  }// 通用优惠券
  else if (req.url.startsWith('/universalCoupon')) {
    jiekou(req, res, '通用优惠券', 'universalCoupon')
  }// 权限
  else if (req.url.startsWith('/rightList')) {
    jiekou(req, res, '权限', 'rightList')
  }
}

// jwt 错误处理
server.use((err, req, res, next) => {
  // 这次错误是由 token 解析失败导致的
  if (err.name === 'UnauthorizedError') {
    return res.send({
      status: 401,
      message: '无效的token',
    })
  }
  res.send({
    status: 500,
    message: '未知的错误',
  })
})


server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})